<template>
  <div ref="serviceTabs">
    <el-tabs v-if="tabsData.length>0" v-model="activeNameItem" type="card" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="(item,index) in tabsData"
        :key="index"
        :label="item.areaName"
        :name="item.areaCode"
      />
    </el-tabs>
    <div v-if="isEdit">
      <div style="display: flex;justify-content: space-between">
        <div style="color: #EB4B4B">
          注意：查询不到服务时表明PMS还未接收到交易系统的服务预估单信息，请咨询商合交易系统确认服务是否已下单采购或采购后项目经理是否完成收货！
        </div>
        <div v-if="showTip" style="color: #606266;">当前子项目{{ prjCode }}已绑定金额{{ money }}元</div>
      </div>
      <div style="margin: 10px 0;display: flex;justify-content: flex-end;align-items: center">
        <el-radio-group v-model="type" class="pms-zr-radio" @input="eleSignInput()">
          <el-radio label="0">单项工程设计方案中返回预估单的服务</el-radio>
          <el-radio label="1">整体项目设计方案中返回预估单的服务</el-radio>
        </el-radio-group>
        <el-button type="primary" class="pms-button-primary" style="margin-left: 10px" @click="designBind">
          按设计方案绑定
        </el-button>
        <el-button v-if="false" type="primary" class="pms-button-primary">导入绑定方案</el-button>
      </div>
    </div>
    <CustomTable
      v-if="flag"
      ref="customTable"
      :column="column"
      :table-data="tableData"
      :table-header="tableHeaderNew"
      :column-arr="columnArr"
      :key-code="keyCode"
      :is-edit="isEdit"
      :prj-params="prjParams"
      @changeStatus="changeStatus"
    />
    <dialog-confirm v-if="visible" :message="message" @changeStatus="changeMsg" />
  </div>
</template>

<script>
import CustomTable from '@/views/acceptanceManagement/materialServiceBind/components/customTable.vue'
import {
    batchUpdateAccState, checkPmServiceBoundingConfirm,
    checkServiceBoundingConfirm, checkServiceBoundingEdit,
    confirmPushServiceBindingToSH,
    queryParentPrjAreaList,
    queryServBoundingList,
    updateServBoundingData, updateServBoundingDataByDesign
} from '@/api/acceptanceManagement/materialServiceBind'
import { msgInfoEl } from '@/utils'
import DialogConfirm from '@/views/acceptanceManagement/materialServiceBind/components/dialogConfirm.vue'

export default {
    name: 'ServiceTabs',
    components: {
        DialogConfirm,
        CustomTable
    },
    props: {
        prjParams: {
            type: Object,
            default: () => ({
            })
        },
        tableHeader: {
            type: Array,
            default: () => []
        },
        isEdit: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            type: '0',
            activeNameItem: '',
            tabsData: [],
            tableData: [],
            column: [
                { label: '服务编码', width: '170', prop: 'serviceCode' },
                { label: '服务名称', width: '90', prop: 'serviceName' },
                { label: '单位', width: '50', prop: 'unit' },
                { label: '设计数量', width: '60', prop: 'amount' },
                { label: '采购订单编号', width: '90', prop: 'orderNo' },
                { label: '供应商名称', width: '90', prop: 'supplier' },
                { label: '合同编码', width: '100', prop: 'contractCode' },
                { label: '商合预占数量', width: '100', prop: 'shNum' },
                { label: '单价（不含税）', width: '100', prop: 'price' },
                { label: '商合预占金额', width: '90', prop: 'shMoney' },
                { label: '绑定数量', width: '60', prop: 'boundNum' },
                { label: '绑定金额', width: '60', prop: 'boundMoney' }
            ],
            keyCode: 'serviceCode',
            columnArr: [1, 2, 3, 4],
            showTip: false, // 右上角提示信息
            prjCode: '', // 右上角提示编码
            money: '', // 右上角提示金额
            tableDataOld: [], // 修改前的数据
            subPrjList: [], // 接口传参时可编辑的子项目流水号集合
            allSubPrjList: [], // 需要展示的表头信息
            tableHeaderNew: [], // 需要根据区域过滤表头
            flag: false, // 表头数据修改时避免不渲染问题
            pageHeight: 384,
            message: [],
            visible: false,
            indexFlag: 0,
            iFlag: 0
        }
    },
    computed: {},
    watch: {
        allSubPrjList: {
            handler(newValue) {
                this.flag = false
                this.$nextTick(() => {
                    this.tableHeaderNew = this.getTableHeader(newValue)
                    this.flag = true
                })
            },
            immediate: true,
            deep: true
        }
    },
    async created() {
        await this.getAreaTabs()
        await this.getTableList()
    },
    methods: {
        getTableHeader(value) {
            const arr = []
            if (value.length > 0) {
              value.forEach((i) => {
                this.tableHeader.forEach((item) => {
                        if (i === item.prjId) {
                            arr.push(item)
                        }
                    })
                })
            }
            return arr
        },
        eleSignInput() {
            this.getTableList()
        },
        handleTabClick(tab) {
            this.subPrjList = this.tabsData[tab.index].subPrjList
            this.allSubPrjList = this.tabsData[tab.index].allSubPrjList
            this.getTableList()
        },
        async getAreaTabs() {
            const tableHeaderPrjList = []
            if (this.tableHeader.length > 0) {
                this.tableHeader.forEach((item) => {
                    tableHeaderPrjList.push(item.prjId)
                })
            }
            const params = {
                subPrjList: this.prjParams.subPrjList,
                allSubPrjList: tableHeaderPrjList
            }
            await queryParentPrjAreaList(params).then((res) => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                this.tabsData = res.data
                if (res.data.length > 0) {
                    this.activeNameItem = res.data[0].areaCode
                    this.subPrjList = res.data[0].subPrjList
                    this.allSubPrjList = res.data[0].allSubPrjList
                }
            })
        },
        getHeaderDataList(item) {
          let arr = []
          this.tableHeaderNew.forEach(item1 => {
            item.singlePrjList.forEach(subItem =>{
              if(item1.prjId=== subItem.prjId){
                arr.push({...subItem})
              }
            });
          })
          return arr
        },
        getDataList(){
          this.tableData.forEach(item => {
            item.singlePrjList=this.getHeaderDataList(item);
          });
          // 也可以先过滤出对应数据，再使用sort进行排序
          // const prjIds = this.tableHeaderNew.map(item => item.prjId);
          // this.tableData.forEach(item => {
          //   item.singlePrjList = item.singlePrjList.filter(subItem => prjIds.includes(subItem.prjId)).sort((a,b)=>prjIds.indexOf(a.prjId)-prjIds.indexOf(b.prjId));
          // });
          this.tableDataOld = JSON.parse(JSON.stringify(this.tableData))
          this.$refs.customTable.getSpanArr(this.tableData)
          console.log(2222,this.tableData)
        },
        // 获取列表数据
        async getTableList() {
            this.tableData = []
            this.tableDataOld = []
            const params = {
                prjId: this.prjParams.parentPrjId,
                prjCode: this.prjParams.parentPrjCode,
                areaCode: this.activeNameItem,
                applyType: this.type,
                subPrjList: this.subPrjList,
                workItemId: this.prjParams.workItemId
            }
            await queryServBoundingList(params).then((res) => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                if (res.data) {
                    console.log(1111,this.tableHeaderNew)
                    this.tableData = res.data
                    this.getDataList()
                }
                this.$nextTick(() => {
                    const h = this.$refs.serviceTabs.clientHeight
                    this.pageHeight = res.data ? h + 130 : 384
                    window.parent.postMessage({ height: this.pageHeight, type: 'materialServiceHeight' }, this.$fixIframeArr())
                    console.log(h, this.pageHeight, 'this.pageHeight-true')
                })
            })
        },
        // 聚焦，失焦之后提示显隐
        changeStatus(data) {
            this.showTip = data.status
            this.prjCode = data.prjCode
            this.money = data.money
            this.indexFlag = data.index
            this.iFlag = data.i
        },
        // 按设计方案进行绑定
        designBind() {
            const params = {
                prjId: this.prjParams.parentPrjId,
                areaCode: this.activeNameItem,
                subPrjList: this.subPrjList
            }
            updateServBoundingDataByDesign(params).then(res => {
                if (+res.code !== 200) {
                    return msgInfoEl({
                        type: 'error',
                        message: res.message
                    }, 3000)
                } else {
                    this.confirmPushServiceBindToSH()
                }
            })
        },
        changeMsg(status) {
            this.visible = false
            if (status) {
                if (this.isEdit) {
                    this.strongCheckServiceBoundConfirm()
                } else {
                    this.strongCheckPmServiceBoundConfirm()
                }
            } else {
                this.getTableList()
            }
        },
        // 监理单位服务绑定校验(弱校验)
        weakCheckServiceBoundConfirm() {
            const params = {
                parentPrjId: this.prjParams.parentPrjId,
                subPrjIds: this.subPrjList,
                checkType: '0'
            }
            checkServiceBoundingConfirm(params).then((res) => {
                if (+res.code === 200) {
                    this.strongCheckServiceBoundConfirm()
                } else {
                    this.message = []
                    if (res.data && res.data.length > 0) {
                        res.data.forEach((item) => {
                            this.message.push(item.msg)
                        })
                    }
                    this.visible = true
                }
            })
        },
        // 监理单位服务绑定校验(强校验)
        strongCheckServiceBoundConfirm() {
            const params = {
                parentPrjId: this.prjParams.parentPrjId,
                subPrjIds: this.subPrjList,
                checkType: '1'
            }
            checkServiceBoundingConfirm(params).then((res) => {
                if (+res.code !== 200) {
                    this.getTableList()
                    return msgInfoEl({
                        type: 'error',
                        message: res.data[0].msg
                    }, 3000)
                } else {
                    // 强校验成功，更新绑定状态
                    this.batchUpdateAccState('101', 'confirm')
                }
            })
        },
        // 项目管理岗绑定校验（弱校验）
        weakCheckPmServiceBoundConfirm() {
            const params = {
                parentPrjId: this.prjParams.parentPrjId,
                subPrjIds: this.subPrjList,
                checkType: '0'
            }
            checkPmServiceBoundingConfirm(params).then((res) => {
                if (+res.code === 200 && !res.data) {
                    this.strongCheckPmServiceBoundConfirm()
                } else {
                    if (+res.code === 4001) {
                      this.getTableList()
                      return msgInfoEl({
                        type: 'error',
                        message: res.data[0].msg
                      }, 3000)
                    } else {
                        this.message = []
                        if (res.data && res.data.length > 0) {
                            res.data.forEach((item) => {
                                this.message.push(item.msg)
                            })
                        }
                        this.visible = true
                    }
                }
            })
        },
        // 项目管理岗服务绑定校验(强校验)
        strongCheckPmServiceBoundConfirm() {
            const params = {
                parentPrjId: this.prjParams.parentPrjId,
                subPrjIds: this.subPrjList,
                checkType: '1'
            }
            checkPmServiceBoundingConfirm(params).then((res) => {
                if (+res.code !== 200) {
                    this.getTableList()
                    return msgInfoEl({
                        type: 'error',
                        message: res.data[0].msg
                    }, 3000)
                } else {
                    // 强校验成功，生成推送
                    if (!res.data) {
                        this.confirmPushServiceBindToSHPm()
                    }
                }
            })
        },
        // 监理单位生成并推送已绑定验工计价且确认绑定状态
        confirmPushServiceBindToSH() {
            const params = this.subPrjList
            confirmPushServiceBindingToSH(params).then((res) => {
                if (+res.code !== 200) {
                    this.getTableList()
                    return msgInfoEl({
                        type: 'error',
                        message: res.data ? res.data[0] : res.message
                    }, 3000)
                }
                this.weakCheckServiceBoundConfirm()
            })
        },
        // 项目管理岗生成并推送已绑定验工计价且确认绑定状态
        confirmPushServiceBindToSHPm() {
            const params = this.subPrjList
            confirmPushServiceBindingToSH(params).then((res) => {
                if (+res.code !== 200) {
                    this.getTableList()
                    return msgInfoEl({
                        type: 'error',
                        message: res.data[0]
                    }, 3000)
                }
                this.batchUpdateAccState('201', 'confirm')
            })
        },
        // 更新绑定状态
        batchUpdateAccState(type, ope) {
            const params = {
                subPrjList: this.subPrjList,
                type: type, // 101监理，201项目管理
                state: ope === 'confirm' ? '1' : '0',
                productType: '1'
            }
            batchUpdateAccState(params).then((res) => {
                this.getTableList()
                if (+res.code !== 200) {
                    return msgInfoEl({
                        type: 'error',
                        message: res.message
                    }, 3000)
                } else {
                    msgInfoEl({
                        type: 'success',
                        message: ope === 'confirm' ? '绑定结果成功！' : '取消确认成功！'
                    }, 3000)
                }
            })
        },
        // 确认绑定结果，父组件调用
        // 监理单位点击确认绑定调：
        // 1.更新服务绑定接口/api/insVa/module/updateServBoundingData，
        // 2.监理单位服务绑定校验/api/insVa/module/checkServiceBoundingConfirm
        // 3.批量更新物资绑定状态（取消确认）/api/bind/product/batchUpdateAccState
        // 项目管理岗点击确认绑定：
        // 1.项目管理岗确认服务绑定校验/api/insVa/module/checkPmServiceBoundingConfirm
        // 2.生成并推送已绑定验工计价且确认绑定状态/api/insVa/module/confirmPushServiceBindingToSH
        // 3.批量更新物资绑定状态（取消确认）/api/bind/product/batchUpdateAccState
        handleSend() {
            if (this.isEdit) {
                if (this.tableData.length > 0) {
                    const paramsObj = {
                        serviceCode: this.tableData[this.indexFlag].serviceCode,
                        num: this.tableData[this.indexFlag].singlePrjList[this.iFlag].subBoundNum,
                        parentPrjId: this.prjParams.parentPrjId
                    }
                    checkServiceBoundingEdit(paramsObj).then((res) => {
                        if (res.check) {
                            this.confirmEdit()
                        }
                    })
                } else {
                    this.confirmEdit()
                }
            } else {
                this.weakCheckPmServiceBoundConfirm()
            }
        },
        confirmEdit() {
            const params = []
            const status = []
            let str = ''
            this.tableData.forEach((item, index) => {
                const arr = []
                item.singlePrjList.forEach((subItem, i) => {
                    if (subItem.isEdit === '1' && subItem.subBoundNum !== null) {
                        arr.push({
                            subPrjId: subItem.prjId,
                            preBoundNum: this.tableDataOld[index].singlePrjList[i].subBoundNum,
                            currentBoundNum: subItem.subBoundNum
                        })
                    }
                })
                if (arr.length > 0) {
                    params.push({
                        serialNum: index + 1,
                        serviceCode: item.serviceCode,
                        orderNo: item.orderNo,
                        orderDetailId: item.orderDetailId || null,
                        subPrjBoundingList: arr
                    })
                }
                if (this.tableData[index].boundNum - this.tableDataOld[index].boundNum <= Number(this.tableData[index].remainNum)) {
                    status.push(true)
                } else {
                    status.push(false)
                    str = str + (index + 1) + ','
                }
            })
            if (status.includes(false)) {
                msgInfoEl({
                    type: 'error',
                    message: `当前页面序号为${str.substring(0, str.length - 1)}数据各个子项目当前绑定数量之和大于整体项目下已返回预估单服务数量，请修改！`
                }, 3000)
            } else {
                // 确认绑定结果,先调更新服务绑定接口
                updateServBoundingData(params).then((res) => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    }
                    this.confirmPushServiceBindToSH()
                })
            }
        },
        // 取消确认，父组件调用
        handleCancel() {
            this.batchUpdateAccState('201', 'cancel')
        }
    }

}
</script>

<style scoped lang="scss">
::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item {
    color: #909399;
}

::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    color: #eb4b4b;
}
</style>
